package test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 多文件压缩
 *
 *
 * @version 1.0
 * @since JDK1.7
 * @author yutao
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
 * @date 2017年5月26日下午1:22:05
 */
public class ZipMuliFile {
	
	
	public static void main(String[] args) throws Exception {
//		String zipFileName = "C:\\Users\\yutao\\Desktop\\pageage\\ziptest.zip";//压缩后的文件
		
		String entry = "C:\\Users\\yutao\\Desktop\\pageage\\test";//需要压缩的文件
		File file = new File(entry);
		
		
		ZipOutputStream zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file.getAbsolutePath() + ".zip")));
		
		String base = file.getName();
		
		compressZip(zipOutput, file, base);
		zipOutput.closeEntry();
		zipOutput.close();
	}

	
	private static void compressZip(ZipOutputStream zipOutput, File file, String base) throws IOException {

		if(file.isDirectory()){
			File[] listFiles = file.listFiles();// 列出所有的文件
			
			for(File fi : listFiles){
				if(fi.isDirectory()){
					compressZip(zipOutput, fi, base + File.separator + fi.getName());
				}else{
					zip(zipOutput, fi, base);
				}
			}
		}else{
			zip(zipOutput, file, base);
		}
	}


	public static void zip(ZipOutputStream zipOutput, File file, String base) throws IOException, FileNotFoundException {
		ZipEntry zEntry = new ZipEntry(base + File.separator + file.getName());
		zipOutput.putNextEntry(zEntry);
		
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		
		byte[] buffer = new byte[1024];
		int read = 0;
		while((read =bis.read(buffer)) != -1){
			zipOutput.write(buffer, 0, read);
		}
		bis.close();
	}

}
